"""
用户认证模型
"""
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils import timezone


class User(AbstractUser):
    """自定义用户模型"""
    
    ROLE_CHOICES = [
        ('admin', '管理员'),
        ('teacher', '就业老师'),
        ('student', '学生'),
    ]
    
    role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='student', verbose_name='角色')
    phone = models.CharField(max_length=20, blank=True, null=True, verbose_name='手机号')
    avatar = models.ImageField(upload_to='avatars/', blank=True, null=True, verbose_name='头像')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    last_login_ip = models.GenericIPAddressField(blank=True, null=True, verbose_name='最后登录IP')
    
    class Meta:
        db_table = 'accounts_user'
        verbose_name = '用户'
        verbose_name_plural = '用户'
        
    def __str__(self):
        return f"{self.username} ({self.get_role_display()})"
    
    @property
    def is_admin(self):
        return self.role == 'admin'
    
    @property
    def is_teacher(self):
        return self.role == 'teacher'
    
    @property
    def is_student(self):
        return self.role == 'student'


class LoginLog(models.Model):
    """登录日志"""

    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    ip_address = models.GenericIPAddressField(verbose_name='IP地址')
    user_agent = models.TextField(verbose_name='用户代理')
    login_time = models.DateTimeField(default=timezone.now, verbose_name='登录时间')
    logout_time = models.DateTimeField(blank=True, null=True, verbose_name='退出时间')
    is_success = models.BooleanField(default=True, verbose_name='是否成功')
    failure_reason = models.CharField(max_length=200, blank=True, null=True, verbose_name='失败原因')
    session_key = models.CharField(max_length=40, blank=True, null=True, verbose_name='会话ID')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'accounts_login_log'
        verbose_name = '登录日志'
        verbose_name_plural = '登录日志'
        ordering = ['-login_time']

    def __str__(self):
        return f"{self.user.username} - {self.login_time}"

    @property
    def is_online(self):
        """是否在线"""
        return self.logout_time is None

    @property
    def duration(self):
        """在线时长（秒）"""
        if self.logout_time:
            return (self.logout_time - self.login_time).total_seconds()
        else:
            return (timezone.now() - self.login_time).total_seconds()


class Permission(models.Model):
    """权限模型"""
    
    name = models.CharField(max_length=100, unique=True, verbose_name='权限名称')
    codename = models.CharField(max_length=100, unique=True, verbose_name='权限代码')
    description = models.TextField(blank=True, null=True, verbose_name='权限描述')
    module = models.CharField(max_length=50, verbose_name='所属模块')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'accounts_permission'
        verbose_name = '权限'
        verbose_name_plural = '权限'
        
    def __str__(self):
        return self.name


class RolePermission(models.Model):
    """角色权限关联"""
    
    role = models.CharField(max_length=20, choices=User.ROLE_CHOICES, verbose_name='角色')
    permission = models.ForeignKey(Permission, on_delete=models.CASCADE, verbose_name='权限')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'accounts_role_permission'
        verbose_name = '角色权限'
        verbose_name_plural = '角色权限'
        unique_together = ['role', 'permission']
        
    def __str__(self):
        return f"{self.get_role_display()} - {self.permission.name}"
